//===========================================================================================================================
// Cuberry - http://www.cuberry.net
// Copyright (c) 2012
// by Peacequare® - Amir Moussa
//===========================================================================================================================
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License 
// as published by the Free Software Foundation, either version 3 of the License, or any later version.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// This program is distributed in the hope that it will be useful.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//===========================================================================================================================

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using Microsoft.Practices.Prism.Commands;
using P2.Cuberry.Framework.Helper;
using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Prism.Regions;
using P2.Cuberry.Modules.SimpleAccounting.FiTransaction.DAL;
using P2.Cuberry.Framework.Helper.Configuration;


namespace P2.Cuberry.Modules.SimpleAccounting.FiTransaction
{
    public class FiChequeEditDetailsPresentationModel : INotifyPropertyChanged, IDisposable, IDataErrorInfo
    {

        public FiChequeEditDetailsPresentationModel(IFiChequeEditDetailsView view, BusinessEntities.FiCheque model, IUnityContainer container, IRegionManager regionManager, int FiTransactionItemID, int FiscalYearID)
        {
            try
            {
                View = view;
                this.Model = model;
                //this.Service = service;
                this.FiTransactionHeaderID = FiTransactionItemID;
                //DDL++

                //added by wli 31-05-2012
                if (Model.FiChequeID < 0)
                {

                    checkforfindoradd = false;

                }
                else
                {
                    BusinessEntities.FiCheque obj = new BusinessEntities.FiCheque();
                    this.FiChequeCreditTransactionItems = obj.GetDataofTransactionitem(this.FiTransactionHeaderID, true, this.ChequeID);

                    checkforfindoradd = true;
                    this.FiChequeDebitTransactionItems = obj.GetDataofTransactionitem(this.FiTransactionHeaderID, false, this.ChequeID);

                }
                //end
                this.XConfigCurrencys = BusinessEntities.XConfigCurrency.GetList;
                this.FiscalYears = P2.Cuberry.Modules.SimpleAccounting.FiAccount.BusinessEntities.FiFiscalYear.GetList;
                this.fichquesList = fichquesList;
                if (this.FiscalYears.Count > 0 && model.FiscalYearID <= 0)
                    this.Model.FiscalYearID = FiscalYearID;

                if (!this.Model.CurrencyID.HasValue)
                {
                    string currIdstr = P2.Cuberry.Framework.Helper.Configuration.ConfigurationSetUp.GetAppConfigValue("FiChequeDefaultCurrency");
                    if (!string.IsNullOrEmpty(currIdstr))
                    {
                        int currId;
                        if (int.TryParse(currIdstr, out currId))
                            this.Model.CurrencyID = currId;
                    }
                }
                ControlRights = Model.GetControls(Properties.Settings.Default.ModuleName, "FiChequeEditDetailsView");
                MessageStack = new P2MessageStack();
                View.Model = this;

                // this.oncheckboxClickCommand = new DelegateCommand<object>(oncheckboxclick, oncheckboxcanclick);
                this.FiChequeSaveCommand = new DelegateCommand<object>(OnFiChequeSaveExecute, OnFiChequeSaveCanExecute);
                this.FiChequeCloseCommand = new DelegateCommand<object>(OnFiChequeCloseExecute, OnFiChequeCloseCanExecute);

                this.InfoCommand = new DelegateCommand<object>(OnInfoExecute, OnInfoCanExecute);
                this.HistoryCommand = new DelegateCommand<object>(OnHistoryExecute, OnHistoryCanExecute);

                this.RefreshView();
            }
            catch (Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }


        #region Members
        public bool checkforfindoradd { get; set; }//added by wli 31-05-2012
        public int ChequeID
        {
            get { return Model.FiChequeID; }
        }

        //Add++
        //added by wli 30-5-2012
        public List<BusinessEntities.FiCheque> fichquesList { get; set; }

        //end
        public int FiscalYearID
        {
            get { return Model.FiscalYearID; }
            set
            {
                if (value != Model.FiscalYearID)
                {
                    Model.FiscalYearID = value;
                    OnPropertyChanged("FiscalYearID");
                }
            }
        }
        int _FiTransactionItemID = 0;
        public int FiTransactionItemID
        {
            get { return _FiTransactionItemID; }
            set
            {

                _FiTransactionItemID = value;

            }
        }
        int _FiTransactionHeaderID = 0;
        public int FiTransactionHeaderID
        {
            get { return _FiTransactionHeaderID; }
            set
            {

                _FiTransactionHeaderID = value;

            }
        }
        public decimal? ChequeNo //check if nullable? 
        {
            get { return Model.ChequeNo; }
            set
            {
                if (value != Model.ChequeNo)
                {
                    Model.ChequeNo = value;
                    OnPropertyChanged("ChequeNo");
                }
            }
        }

        public string Bank //check if nullable? 
        {
            get { return Model.Bank; }
            set
            {
                if (value != Model.Bank)
                {
                    Model.Bank = value;
                    OnPropertyChanged("Bank");
                }
            }
        }

        public string MyBank //check if nullable? 
        {
            get { return Model.MyBank; }
            set
            {
                if (value != Model.MyBank)
                {
                    Model.MyBank = value;
                    OnPropertyChanged("MyBank");
                }
            }
        }
        public DateTime? ValueDate //check if nullable? 
        {
            get { return Model.ValueDate; }
            set
            {
                if (value != Model.ValueDate)
                {
                    Model.ValueDate = value;
                    OnPropertyChanged("ValueDate");
                }
            }
        }

        public decimal? Amount //check if nullable? 
        {
            get { return Model.Amount; }
            set
            {
                if (value != Model.Amount)
                {
                    Model.Amount = value;
                    OnPropertyChanged("Amount");
                }
            }
        }

        public int? FiTransactionID //check if nullable? 
        {
            get { return Model.FiTransactionID; }
            set
            {
                if (value != Model.FiTransactionID)
                {
                    Model.FiTransactionID = value;
                    OnPropertyChanged("FiTransactionID");
                }
            }
        }

        public string Note //check if nullable? 
        {
            get { return Model.Note; }
            set
            {
                if (value != Model.Note)
                {
                    Model.Note = value;
                    OnPropertyChanged("Note");
                }
            }
        }





        //DDL++

        public int CurrencyID //check if nullable? 
        {
            get { return Model.CurrencyID.GetValueOrDefault(-1); }
            set
            {
                if (value != Model.CurrencyID)
                {
                    if (value == -1)
                        Model.CurrencyID = null;
                    else
                        Model.CurrencyID = value;
                    OnPropertyChanged("CurrencyID");
                }
            }
        }

        //added by wli 31-5-2012

        public ObservableCollection<FiTransaction.BusinessEntities.FiTransactionItem> FiChequeCreditTransactionItems { get; set; }

        public ObservableCollection<FiTransaction.BusinessEntities.FiTransactionItem> FiChequeDebitTransactionItems { get; set; }


        public decimal DebitTransactionSum
        {
            get
            {
                if (FiChequeDebitTransactionItems != null && FiChequeDebitTransactionItems.Count > 0)
                {
                    decimal summary = 0;
                    foreach (var tempItem in FiChequeDebitTransactionItems)
                    {
                        if (tempItem.FiTransactionItemAdd == true)
                        {
                            summary += tempItem.FiAccountAmountDebit;
                        }
                    }

                    return summary;
                }
                else
                {
                    return 0;
                }
            }

        }


        public decimal CreditTransactionSum
        {
            get
            {
                if (FiChequeCreditTransactionItems != null && FiChequeCreditTransactionItems.Count > 0)
                {
                    decimal summary = 0;
                    foreach (var tempItem in FiChequeCreditTransactionItems)
                    {
                        if (tempItem.FiTransactionItemAdd == true)
                        {
                            summary += tempItem.FiAccountAmountCredit;
                        }
                    }
                    return summary;
                }
                else
                {
                    return 0;
                }
            }
        }

        //end

        #endregion


        #region Computed Members

        public string StatusName
        {
            get { return Model.CurrentStatus.StatusNameCur; }
        }

        public bool ModelIsModified
        {
            get
            {
                return Model.Modified;
            }
        }

        //public bool IsReadOnly
        //{
        //    get
        //    {
        //        P2.Cuberry.Framework.Security.User.ControlRight controlRight;
        //        if (ControlRights.TryGetValue("FiChequeSaveBtn", out controlRight))
        //            return !controlRight.IsActive;
        //        else
        //            return true;
        //    }
        //}

        //public bool IsEditable
        //{
        //    get
        //    {
        //        return !IsReadOnly;
        //    }
        //}

        #endregion


        #region Reference Tables

        //DDL++
        public List<BusinessEntities.XConfigCurrency> XConfigCurrencys { get; set; }
        public List<P2.Cuberry.Modules.SimpleAccounting.FiAccount.BusinessEntities.FiFiscalYear> FiscalYears { get; set; }

        //public List<P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus> WorkflowStatusses { get; set; }

        #endregion


        #region Commands

        public DelegateCommand<object> FiChequeSaveCommand { get; set; }
        public DelegateCommand<object> FiChequeCloseCommand { get; set; }
        public DelegateCommand<object> oncheckboxClickCommand { get; set; }


        public DelegateCommand<object> InfoCommand { get; set; }
        public DelegateCommand<object> HistoryCommand { get; set; }

        //added by wli 31-5-2012

        void oncheckboxclick(object sourceAccount)
        {

            try
            {
            }
            catch (Exception)
            {
                throw;
            }
        }

        void OnFiChequeSaveExecute(object sourceAccount)
        {
            View.UpdateFocusedControl();
            bool validationOK = this.Save();
            
            //added by wli 31-5-2012
            if (checkforfindoradd == false)
            {
                BusinessEntities.FiCheque objficheques = new BusinessEntities.FiCheque();
                BusinessEntities.FiChequeToFiTransactionItem obj = new BusinessEntities.FiChequeToFiTransactionItem();
                if (validationOK)
                {
                    FiChequeCreditTransactionItems = objficheques.GetDataofTransactionitem(this.FiTransactionHeaderID, true, Model.FiChequeID);
                    FiChequeDebitTransactionItems = objficheques.GetDataofTransactionitem(this.FiTransactionHeaderID, false, Model.FiChequeID);
                }
                objficheques.OnAllPropertiesChanged();
                obj.OnAllPropertiesChanged();
                Model.Modified = true;

                OnPropertyChanged("FiChequeCreditTransactionItems");
                OnPropertyChanged("FiChequeDebitTransactionItems");
                //this.RefreshView();

                View.Model = this;
            }
            else
            {
                foreach (var fi in FiChequeCreditTransactionItems)
                {
                    bool foradd = false;
                    if (fi.FiTransactionItemAdd == true && fi.FiTransactionItemCheckForReadOnly == true)
                    {
                        View.UpdateFocusedControl();
                        foradd = true;
                        this.SaveFiChequeToFiTransactionItems(Model.FiChequeID, fi.FiTransactionItemID, Model.FiscalYearID, foradd);
                    }
                    else if (fi.FiTransactionItemAdd == false && fi.FiTransactionItemCheckForReadOnly == true)
                    {
                        foradd = false;
                        View.UpdateFocusedControl();
                        this.SaveFiChequeToFiTransactionItems(Model.FiChequeID, fi.FiTransactionItemID, Model.FiscalYearID, foradd);
                    }
                }

                foreach (var fi in this.FiChequeDebitTransactionItems)
                {
                    bool foradd = false;
                    if (fi.FiTransactionItemAdd == true && fi.FiTransactionItemCheckForReadOnly == true)
                    {
                        View.UpdateFocusedControl();
                        foradd = true;
                        this.SaveFiChequeToFiTransactionItems(Model.FiChequeID, fi.FiTransactionItemID, Model.FiscalYearID, foradd);
                    }
                    else if (fi.FiTransactionItemAdd == false && fi.FiTransactionItemCheckForReadOnly == true)
                    {
                        foradd = false;
                        View.UpdateFocusedControl();
                        this.SaveFiChequeToFiTransactionItems(Model.FiChequeID, fi.FiTransactionItemID, Model.FiscalYearID, foradd);
                    }
                }
            }

            View.Model = this;
            //end
            //checkforfindoradd = true;

            return;
        }


        bool OnFiChequeSaveCanExecute(object sourceAccount)
        {
            P2.Cuberry.Framework.Security.User.ControlRight controlRight;
            if (ControlRights.TryGetValue("FiChequeSaveBtn", out controlRight))
                return controlRight.IsActive;
            else
                return false;
        }


        //added by wli 30-5-2012
        void OnFiChequeCloseExecute(object sourceAccount)
        {
            View.UpdateFocusedControl();
            if (this.Save())
            {
                //start

                foreach (var fi in FiChequeCreditTransactionItems)
                {
                    if (fi.FiTransactionItemAdd == true && fi.FiTransactionItemCheckForReadOnly == true)
                    {
                        bool foradd = false;
                        if (fi.FiTransactionItemAdd == true && fi.FiTransactionItemCheckForReadOnly == true)
                        {
                            View.UpdateFocusedControl();
                            foradd = true;
                            this.SaveFiChequeToFiTransactionItems(Model.FiChequeID, fi.FiTransactionItemID, Model.FiscalYearID, foradd);

                        }
                        else if (fi.FiTransactionItemAdd == false && fi.FiTransactionItemCheckForReadOnly == true)
                        {
                            foradd = false;

                            View.UpdateFocusedControl();
                            this.SaveFiChequeToFiTransactionItems(Model.FiChequeID, fi.FiTransactionItemID, Model.FiscalYearID, foradd);

                        }
                    }
                }
                foreach (var fi in this.FiChequeDebitTransactionItems)
                {
                    bool foradd = false;
                    if (fi.FiTransactionItemAdd == true && fi.FiTransactionItemCheckForReadOnly == true)
                    {
                        View.UpdateFocusedControl();
                        foradd = true;
                        this.SaveFiChequeToFiTransactionItems(Model.FiChequeID, fi.FiTransactionItemID, Model.FiscalYearID, foradd);

                    }
                    else if (fi.FiTransactionItemAdd == false && fi.FiTransactionItemCheckForReadOnly == true)
                    {
                        foradd = false;

                        View.UpdateFocusedControl();
                        this.SaveFiChequeToFiTransactionItems(Model.FiChequeID, fi.FiTransactionItemID, Model.FiscalYearID, foradd);

                    }
                }


                //end
                View.Close();
            }
        }
        //end
        bool OnFiChequeCloseCanExecute(object sourceAccount)
        {
            P2.Cuberry.Framework.Security.User.ControlRight controlRight;
            if (ControlRights.TryGetValue("FiChequeSaveBtn", out controlRight))
                return controlRight.IsActive;
            else
                return false;
        }




        void OnInfoExecute(object sourceItem)
        {           
            Model.GetObjectInfo();
            return;
        }

        bool OnInfoCanExecute(object sourceItem)
        {
            return true;
        }


        bool OnHistoryCanExecute(object sourceItem)
        {
            return true;
        }

        void OnHistoryExecute(object sourceItem)
        {
            Model.GetObjectHistory("FiCheque", "FiCheque", this.Model.FiChequeID);
            return;
        }

        //Add++
        public void RefreshView()
        {
            try
            {
                ControlRights = Model.GetControls(Properties.Settings.Default.ModuleName, "FiChequeEditDetailsView");
                OnPropertyChanged("FiChequeID");
                OnPropertyChanged("FiscalYearID");
                OnPropertyChanged("ChequeNo");
                OnPropertyChanged("Bank");
                OnPropertyChanged("MyBank");
                OnPropertyChanged("ValueDate");
                OnPropertyChanged("Amount");
                OnPropertyChanged("FiTransactionID");
                OnPropertyChanged("Note");

                //Standard Fields
                OnPropertyChanged("StatusName");


                //added by wli 30-5-2012

                //OnPropertyChanged("FiTransactionItemAdd");
                //OnPropertyChanged("BookingDescriptionHeader");
                //OnPropertyChanged("FiAccountNo");
                //OnPropertyChanged("FiAccountNameCur");
                //OnPropertyChanged("FiAccountAmountCredit");
                //OnPropertyChanged("FiAccountAmountDebit");
                //OnPropertyChanged("DebitTransactionSum");
                //OnPropertyChanged("CreditTransactionSum");

                //end

                this.FiChequeCloseCommand.RaiseCanExecuteChanged();
                this.FiChequeSaveCommand.RaiseCanExecuteChanged();
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }


        public bool Save()
        {
            bool isNewItem = (this.ChequeID <= 0);
            MessageStack.Clear();
            Model.InsertAndUpdate(MessageStack, true);

            if (MessageStack.StatusMessage.MessageStatus != P2ValidationStatus.red && !Model.Modified)
            {
                return true;
            }
            else
                return false;
        }



        //added by wli 30-5-2012
        public bool SaveFiChequeToFiTransactionItems(int chequeid, int transactionItemid, int FiscalYearID, bool foradd)
        {
            //  bool isNewItem = (this.ChequeID == 0);
            MessageStack.Clear();
            BusinessEntities.FiChequeToFiTransactionItem obj = new BusinessEntities.FiChequeToFiTransactionItem();

            string connectionString = ConfigurationSetUp.GetEntConnectionString("Business", Properties.Settings.Default.EntityResources);

            bool checkforadd = false;
            using(FiTransactionDataModelDataContext db = new FiTransactionDataModelDataContext(connectionString))
            {
                checkforadd = db.FiChequeToFiTransactionItem.Where(c => c.FiTransactionItemID == transactionItemid && c.FiChequeID == chequeid).Select(c => c).ToList().Count > 0 ? false : true;
            }
            if(checkforadd == true)
            {
                obj.InsertAndUpdate(MessageStack, true, chequeid, transactionItemid, FiscalYearID,foradd);
            }
            else if (foradd == false && checkforadd == false)
            {
                using(FiTransactionDataModelDataContext db = new FiTransactionDataModelDataContext(connectionString))
                {
                    obj.InsertAndUpdate(MessageStack, true, chequeid, transactionItemid, FiscalYearID, foradd);
                }
            }

            if (MessageStack.StatusMessage.MessageStatus != P2ValidationStatus.red && !Model.Modified)
            {
                return true;
            }
            else
                return false;
        }


        //Find++
        public ObservableCollection<BusinessEntities.FiCheque> GetCheques()
        {
            ObservableCollection<BusinessEntities.FiCheque> _myItemDT = Service.RetrieveCheques();
            var ordered = _myItemDT; //.OrderBy(f => f.FirstNameEn); --->>> If they have to be sorted!
            ObservableCollection<BusinessEntities.FiCheque> result = new ObservableCollection<BusinessEntities.FiCheque>();

            foreach (var xItem in ordered)
            {
                result.Add(xItem);
            }
            return result;
        }

        #endregion


        #region Model & View Components

        public IFiChequeEditDetailsView View { get; set; }

        public Services.IFiChequeService Service;
        public BusinessEntities.FiCheque Model { get; set; }
        public Dictionary<string, P2.Cuberry.Framework.Security.User.ControlRight> ControlRights;
        private IEventAggregator eventAggregator;
        public bool IsOpenedFromTransaction = false;
        protected P2MessageStack myMessageStack = new P2MessageStack();
        public P2MessageStack MessageStack
        {
            get
            {
                return myMessageStack;
            }
            set
            {
                myMessageStack = value;
                OnPropertyChanged("MessageStack");
            }
        }

        #endregion


        #region Property Changed

        public event PropertyChangedEventHandler PropertyChanged;


        private void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler Handler = PropertyChanged;
            if (Handler != null) Handler(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion


        #region IDisposable Members

        public void Dispose()
        {
            if (View != null)
                View.Model = this;
            View = null;
            this.Model = null;
            this.Service = null;
        }

        #endregion


        #region Error Handling

        public string Error
        {
            get { throw new NotImplementedException(); }
        }

        public string this[string columnName]
        {
            get
            {
                string result = null;

                P2MessageStack propertyMessageStack = this.Model.Validator.ValidateProperty(this.Model, columnName);
                if (propertyMessageStack != null && propertyMessageStack.Count > 0)
                {
                    foreach (P2TransactionMessage message in propertyMessageStack)
                    {
                        if (message.TransactionStatus != "green")
                        {
                            if (result == null)
                                result = message.MessageText;
                            else
                                result += "\n" + message.MessageText;
                        }
                    }
                }
                return result;
            }
        }

        #endregion


    }
}

